#include "remiadddialog.h"
#include "ui_remiadddialog.h"

RemiAddDialog::RemiAddDialog(QWidget *parent, QString *objektnr, QString *titel, QString gtin) :
    QDialog(parent),
    ui(new Ui::RemiAddDialog)
{
    ui->setupUi(this);
    ui->progressBar->hide();
    this->resize(width(), minimumHeight());

    search_results = new QListWidget();
    search_results->setSortingEnabled(true);
    QVBoxLayout *layout = new QVBoxLayout();
    layout->setContentsMargins(0,0,0,0);
    layout->addWidget(search_results);
    search_popup = new QFrame(this, Qt::Tool|Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    search_popup->setAttribute(Qt::WA_DeleteOnClose);
    search_popup->setLayout(layout);
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(Qt::red));
    search_results->setPalette(palette);

    ui->titel_lineEdit->installEventFilter(this);
    search_results->installEventFilter(this);

    this->objektnr = objektnr;
    this->titel = titel;
    this->gtin = gtin;
    current_objectnr = "rt" + da.getVdznr(gtin);

    search_reply = 0;

    search_timer = new QTimer();
    search_timer->setSingleShot(true);
    connect(search_timer, SIGNAL(timeout()), this, SLOT(searchOnline()));
}

RemiAddDialog::~RemiAddDialog()
{
    delete ui;
}

bool RemiAddDialog::event(QEvent *e)
{
    if ( e->type() == QEvent::Hide )
    {
        search_timer->stop();

        if ( search_reply )
            search_reply->abort();

        search_popup->hide();
    }

    return QDialog::event(e);
}

bool RemiAddDialog::eventFilter(QObject *object, QEvent *event)
{
    if ( object == ui->titel_lineEdit )
    {
        if ( event->type() == QEvent::KeyPress )
        {
            switch (static_cast<QKeyEvent*>(event)->key())
            {
            case Qt::Key_Up:
                search_results->setCurrentRow( (search_results->currentRow()>0)?search_results->currentRow()-1:search_results->count()-1 );
                return true;
            case Qt::Key_Down:
                search_results->setCurrentRow( (search_results->currentRow()<search_results->count()-1)?search_results->currentRow()+1:0 );
                return true;
            case Qt::Key_PageUp:
                search_results->setCurrentRow( (search_results->currentRow()-5>=0)?search_results->currentRow()-5:0 );
                return true;
            case Qt::Key_PageDown:
                search_results->setCurrentRow( (search_results->currentRow()+5<search_results->count())?search_results->currentRow()+5:search_results->count()-1 );
                return true;
            case Qt::Key_Return:
            case Qt::Key_Enter:
                if ( search_popup->isVisible() && !search_results->selectedItems().isEmpty() )
                {
                    ui->titel_lineEdit->setText( search_results->currentItem()->text() );
                    current_objectnr = search_results->currentItem()->data(Qt::UserRole).toString();
                    search_popup->hide();
                    return true;
                }
                return false;
            case Qt::Key_Escape:
                if ( search_reply && search_reply->isRunning() )
                {
                    search_reply->abort();
                    return true;
                }
                if ( search_popup->isVisible() )
                {
                    search_popup->hide();
                    return true;
                }
                return false;
            }
        }
    }

    if ( object == search_results )
    {
        if ( event->type() == QEvent::KeyPress )
        {
            switch (static_cast<QKeyEvent*>(event)->key())
            {
            case Qt::Key_Return:
            case Qt::Key_Enter:
                if ( search_popup->isVisible() && !search_results->selectedItems().isEmpty() )
                {
                    ui->titel_lineEdit->setText( search_results->currentItem()->text() );
                    current_objectnr = search_results->currentItem()->data(Qt::UserRole).toString();
                    search_popup->hide();
                    return true;
                }
            }
        }

        if ( event->type() == QEvent::MouseButtonDblClick &&
             static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton &&
             !search_results->selectedItems().isEmpty() )
        {
            ui->titel_lineEdit->setText( search_results->currentItem()->text() );
            current_objectnr = search_results->currentItem()->data(Qt::UserRole).toString();
            search_popup->hide();
            return true;
        }
    }

    return false;
}

void RemiAddDialog::moveEvent(QMoveEvent *)
{
    if ( search_popup->isVisible() )
        search_popup->move(this->geometry().x()+ui->titel_lineEdit->geometry().x(), this->geometry().y()+ui->titel_lineEdit->geometry().y()+ui->titel_lineEdit->height());
}

void RemiAddDialog::searchOnline()
{
    QString search_string = ui->titel_lineEdit->text();
    search_string.replace("ä", "aeae");
    search_string.replace("ö", "oeoe");
    search_string.replace("ü", "ueue");
    search_string.replace("ß", ".ssss.");
    QByteArray data;
    data.append("titelsuche=");
    data.append(QUrl::toPercentEncoding(search_string));
    QNetworkRequest r(QUrl("http://www.leverdy.de/prod_titelsuche.php"));
    r.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    r.setPriority(QNetworkRequest::HighPriority);
    search_reply = Rt::oc->getManager()->post(r, data);
    connect(search_reply, SIGNAL(finished()), this, SLOT(searchReplyFinished()));
    ui->progressBar->show();
}

void RemiAddDialog::searchReplyFinished()
{
    disconnect(search_reply, SIGNAL(finished()), this, SLOT(searchReplyFinished()));
    ui->progressBar->hide();
    if ( search_reply->error() == QNetworkReply::NoError )
    {
        search_results->clear();
        QWebPage page;
        page.currentFrame()->setHtml( QString::fromLatin1(search_reply->readAll()) );
        QWebElementCollection dom_tr_collection = page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().findAll("tr");
        QList<QString> objektnrn;
        foreach ( QWebElement dom_tr, dom_tr_collection )
        {
            QWebElement dom_a = dom_tr.findFirst("a");
            QRegExp rx("objektnr=([\\d]{1,6})");
            dom_a.attribute("href").contains(rx);

            if ( !objektnrn.contains(rx.cap(1)) )
            {
                objektnrn.append(rx.cap(1));
                QListWidgetItem *item = new QListWidgetItem( dom_a.toPlainText().simplified() );
                item->setData(Qt::UserRole, rx.cap(1));
                search_results->addItem(item);
            }
        }
        if ( search_results->count() > 0 )
        {
            search_popup->setGeometry(this->geometry().x()+ui->titel_lineEdit->geometry().x(), this->geometry().y()+ui->titel_lineEdit->geometry().y()+ui->titel_lineEdit->height(), ui->titel_lineEdit->width(), 140);
            search_popup->show();
        }
    }
}

void RemiAddDialog::on_titel_lineEdit_textEdited(const QString &string)
{
    current_objectnr = "rt" + da.getVdznr(gtin);

    if ( Rt::oc->isLogedIn() )
    {
        search_popup->hide();

        if ( search_reply )
            search_reply->abort();

        if ( string.length() >= 3 && !da.isGTIN(string) )
            search_timer->start(500);
    }
}

void RemiAddDialog::on_buttonBox_accepted()
{
    if ( !da.isGTIN(ui->titel_lineEdit->text()) && ui->titel_lineEdit->text().count() >= 3 )
    {
        titel->operator =( ui->titel_lineEdit->text() );
        objektnr->operator =( current_objectnr );
        accept();
    }
}
